<?php
if (!defined('IN_CONTEXT')) die('access violation error!');

class lib_front
{
	public static $_debug;
	public static $_controller;
	public static $_action;
	
	public static function dispatch()
	{
		self::setDebug();
		$_debug = self::getDebug();
		lib_toolkit::filterSpace();
		
		if(empty($_REQUEST['_m']) && empty($_REQUEST['_a']))
		{
			$_controller = 'controller_index'; 
			$_action = 'index';
		}
		else
		{
			$_controller = empty($_REQUEST['_m']) ? 'controller_index' : 'controller_'.trim($_REQUEST['_m']);//url中_m最好不要有_符号
			$_action = empty($_REQUEST['_a']) ? 'index' : trim($_REQUEST['_a']);
		}
		
		self::$_controller = $_controller;
		self::$_action = $_action;
		self::filter();
		
		try
		{
			$controller = new $_controller();
			$reflection = new ReflectionClass($_controller);
			if($reflection->hasMethod($_action))
			{
				$controller->init($_action);
				$_view = $controller->$_action();
				if(empty($_view)) $_view = $_action;
				
				$tmp = strlen($_controller)-strlen('controller_');
				$tmp = substr($_controller,-1 * $tmp,$tmp);
				$_view_file = "./view/$tmp/$_view.php";
				if(!file_exists($_view_file)) die("Can not find this file: $_view_file.");
				
				if($reflection->hasProperty('_layout'))
				{
					$layout = $controller->getLayout();
				}
				else
				{
					$layout = 'init';
				}
				
				$_layout_file = "./view/common/{$layout}.php";
				if(!file_exists($_layout_file)) die("Can not find this file: $_layout_file.");
				
				$view_arr = $controller->getValues();
				if(!empty($view_arr))
				{
					foreach($view_arr as $k => $v)
					{
						$$k = $v;
					}
				}
				
				include_once($_layout_file);
			}
			else
			{
				if($_debug)
				{
					die("Can not find this action: $_action.");
				}
				else
				{
					die("Can not parse url address.");
				}
			}
		}
		catch(Exception $ex)
		{
			if($_debug)
			{
				die($ex->getMessage());
			}
			else
			{
				die("Can not parse url address.");
			}
		}
	}
	
	public static function filter()
	{
		//-------------filter user login or not----------------
		$bool = lib_toolkit::islogin();
		if(!$bool)
		{
			if(!((self::$_controller == 'controller_index' && self::$_action == 'index') || (self::$_controller == 'controller_index' && self::$_action == 'dologin')))
			{
				@header('Location: ./index.php');
				die;
			}
		}
		//-------------filter user login or not----------------
	}
	
	public static function setDebug()
	{
		$xmlObj = lib_xml::init();
		self::$_debug = $xmlObj->getConfig('data/debug');//获取调试信息
	}
	
	public static function getDebug()
	{
		return self::$_debug;
	}
}
?>